<template>
    <div>
        <!-- 右侧悬浮折叠信息窗 -->
        <div class="collapse-box">
            <button class="toggle-button" @click="toggleCollapse">
                <span :class="isCollapse?'el-icon-notebook-2':'el-icon-caret-right'" style="margin-bottom: 5px" />
                <span>{{isCollapse?'数据记录':'收起窗口'}}</span>
            </button>
            <div :class="isCollapse?'collapse-box-hide':'collapse-box-hide collapse-box-active'">
                <div v-if="isShowFont">
                    <ul class="note-ul" v-if="accountRecords && accountData.data">
                        <li class="note-li" v-for="(item,index) in accountRecords">
                            <span class="note-highlight-blue"> {{getAccountNameByID(item.userId)}} </span>于
                            <span class="note-highlight-blue"> {{item.date}} </span>
                            <span :class="getBehaviorClass(item.behavior)"> {{getBehavior(item.behavior)}} </span>了账户对象：
                            <span class="note-highlight-blue"> {{item.targetId}} </span>
                        </li>
                    </ul>
                </div>
            </div>
        </div>
        <!-- 控制Table行的悬浮窗口 -->
        <div :class="floatBoxVisible?'float-box float-box-active':'float-box'">
            <button class="float-button" @click="tableBackup">
                <span class="el-icon-top"></span>
            </button>
            <button class="float-button" @click="tablePutdown">
                <span class="el-icon-bottom"></span>
            </button>
        </div>
        <!--高级搜索抽屉-->
        <el-drawer title="高级搜索" size="30%" :before-close="handleClose" :visible.sync="drawerState" direction="rtl" custom-class="demo-drawer" ref="drawer">
            <el-container>
                <el-main>
                    <el-form :model="userParam" status-icon id="seniorSearchDrawer" ref="selectForm" :rules="selectFormRule">
                        <el-row type="flex" justify="center">
                            <el-col :span="20">
                                <el-form-item label="账户ID" prop="userId" label-width="80px">
                                    <el-input v-model="userParam.userId" auto-complete="off"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row type="flex" justify="center">
                            <el-col :span="20">
                                <el-form-item label="账户名称" label-width="80px">
                                    <el-input v-model="userParam.userName" autocomplete="off"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row type="flex" justify="center">
                            <el-col :span="20">
                                <el-form-item label="账户权限" label-width="80px">
                                    <el-select v-model="userParam.levelId" placeholder="请选择权限">
                                        <el-option label="管理员" value="1"></el-option>
                                        <el-option label="普通用户" value="2"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row type="flex" justify="center">
                            <el-col :span="20">
                                <el-form-item label="登录IP" label-width="80px">
                                    <InputIP @inputValue="getTotalIP"></InputIP>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row type="flex" justify="center">
                            <el-col :span="20">
                                <el-form-item label="登录时间" label-width="80px">
                                    <el-date-picker
                                        v-model="userParam.DateScope"
                                        value-format="yyyy-MM-dd HH:mm:ss"
                                        type="datetimerange"
                                        :picker-options="pickerOptions"
                                        range-separator="至"
                                        start-placeholder="开始日期"
                                        end-placeholder="结束日期"
                                        align="right">
                                    </el-date-picker>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </el-main>
                <el-footer>
                    <el-row type="flex" justify="end">
                        <el-col :span="5">
                            <el-button @click="cancelForm">取 消</el-button>
                        </el-col>
                        <el-col :span="5">
                            <el-button type="primary" @click="$refs.drawer.closeDrawer()" :loading="drawerLoading">{{ drawerLoading ? '搜索中 ...' : '提交搜索' }}</el-button>
                        </el-col>
                    </el-row>
                </el-footer>
            </el-container>
        </el-drawer>
        <!--添加/搜索-->
        <el-row :gutter="20" class="tool-row">
            <el-col :xl="5" :lg="5" :md="5" :sm="7" :xs="7">
                <el-input size="small" placeholder="用户名..."
                          suffix-icon="el-icon-s-custom"
                          maxlength="12"
                          show-word-limit
                          v-model="userParam.userName"/>
            </el-col>
            <el-col :xl="2" :lg="2" :md="3" :sm="3" :xs="7">
                <el-button type="primary" size="small" icon="el-icon-plus" @click="accountAdd">添加</el-button>
            </el-col>
            <el-col :xl="9" :lg="9" :md="6" :sm="5" class="hidden-xs-only">
                <span class="span-font">当前显示：{{countDisplay}}</span>
            </el-col>
            <el-col :xl="4" :lg="4" :md="4" :sm="6" :xs="6">
                <el-input v-model="userParam.userName" size="small" placeholder="按用户名搜索..."/>
            </el-col>
            <el-col :xl="2" :lg="2" :md="3" :sm="3" :xs="3">
                <el-button type="primary" size="small" icon="el-icon-search" @click="normalSelect">搜索</el-button>
            </el-col>
            <el-col :xl="2" :lg="2" :md="3" class="hidden-sm-and-down">
                <el-button type="primary" size="small" icon="el-icon-link" @click="openDrawer">高级搜索</el-button>
            </el-col>
        </el-row>
        <!--table-->
        <el-table :data="this.accountData.data" style="width: 100%;margin-top: 10px" :height="tableHeight"
                  ref="accountTable"
                  v-el-table-infinite-scroll="accountLoad"
                  infinite-scroll-distance="10px"
                  infinite-scroll-delay="100"
                  :border="true"
                  :row-class-name="tableRowClassName"
                  header-cell-class-name="header-cell"
                  v-loading="tableLoading">
            <el-table-column prop="userId" label="ID" width="100" sortable></el-table-column>
            <el-table-column prop="userName" label="姓名" width="100" sortable></el-table-column>
            <el-table-column prop="loginIp" label="上次登录IP" width="130" align="center" header-align="left" sortable></el-table-column>
            <el-table-column prop="loginTime" label="上次登录日期" width="180" align="center" header-align="left" sortable></el-table-column>
            <el-table-column prop="registerDate" label="创建日期" width="180" align="center" header-align="left" sortable></el-table-column>
            <el-table-column prop="role.levelDescribe" label="权限" width="100" sortable align="center" header-align="left"/>
            <el-table-column prop="enable" label="账户状态" width="110" sortable align="center" header-align="left">
                <template slot-scope="scope">
                    <span v-if="scope.row.enable" style="color: #68c176">激活</span>
                    <span v-if="!scope.row.enable" style="color: #e05e5e">禁用</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="230" align="center" header-align="left">
                <template slot-scope="scope">
                    <el-button v-if="!scope.row.enable" size="mini" type="primary" icon="el-icon-video-play" class="table-cell-button"
                               @click="enableReverse(scope.$index,scope.row)">解除禁用</el-button>
                    <el-button v-if="scope.row.enable" size="mini" type="danger" icon="el-icon-video-pause" class="table-cell-button table-cell-button-alert"
                               @click="enableReverse(scope.$index,scope.row)">禁用账户</el-button>
                    <el-popconfirm title="确定要重置该账户吗?" confirm-button-text="确定" cancel-button-text="取消"
                                   @confirm="reset(scope.$index,scope.row)"
                                   icon-color="red"
                                   icon="el-icon-info">
                        <el-button size="mini" type="danger" icon="el-icon-warning" slot="reference" class="table-cell-button">重 置</el-button>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
    </div>
</template>

<script>
import elTableInfiniteScroll from "el-table-infinite-scroll";
import InputIP from "../components/AccountDataComponents/input-IP";
import {mapState,mapActions} from 'vuex'

export default {
    name: "AccountData",
    components: {
        InputIP
    },
    directives: {
        'el-table-infinite-scroll': elTableInfiniteScroll
    },
    data(){
        let validateId = (rule,value,callback)=>{
            if(value!== ''){
                let reg = /^[0-9]\d*$/;
                if(reg.test(value * 1)){
                    callback();
                }else{
                    callback(new Error("请输入数据的正整数编号"));
                }
            }
            callback();
        }
        return{
            userParam: {
                currentPage: 1,
                pageSize: 20,
                userId: '',
                userName: '',
                loginIp: '',
                levelId: '',
                DateScope: []
            },
            floatBoxVisible: false,
            drawerState: false,
            drawerLoading: false,
            isCollapse: true,
            isShowFont: false,
            timer: null,
            tableLoading: false,
            tableHeight: null,
            //用于提交搜索条件的表单验证规则
            selectFormRule: {
                userId: [
                    {validator: validateId, trigger: 'blur'}
                ]
            },
            //供日期选择器快捷选项使用
            pickerOptions: {
                shortcuts: [{
                    text: '最近一周',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近一个月',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近三个月',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                        picker.$emit('pick', [start, end]);
                    }
                }]
            },
        }
    },
    methods:{
        ...mapActions([
            'updateAccountsParam',
            'initAccounts',
            'selectAccounts',
            'addAccount',
            'addAccounts',
            'reverseAccountEnable',
            'resetAccount'
        ]),
        accountAdd() {
            if (this.userParam.userName) {
                //调用存放在actions中的添加账户方法
                this.addAccount(this.userParam);
                //重置input框内容
                this.userParam.userName='';
            }else{
                this.$message.warning("姓名不能为空!");
            }
        },
        getTableHeight(){
            this.tableHeight = window.innerHeight - 60 - (40 + 14 + 30) - (33 + 20) + 30;
        },
        tableRowClassName({row,rowIndex}) {
            if ((rowIndex + 1) % 3 === 0) {
                if ((rowIndex + 1) / 3 % 2 === 0) {
                    return 'row-background-default row-background-blue'
                } else {
                    return 'row-background-default row-background-grey'
                }
            } else {
                return 'row-background-default'
            }
        },
        tableBackup(){
            // this.$refs.accountTable.bodyWrapper.scrollTop = 0;
            let dom = this.$refs.accountTable;
            let step = Math.ceil(dom.bodyWrapper.scrollTop / 15);
            let timer = setInterval(function (){
                let nowPosition = dom.bodyWrapper.scrollTop;
                if(nowPosition > step){
                    dom.bodyWrapper.scrollTop = nowPosition - step;
                }else{
                    dom.bodyWrapper.scrollTop = 0;
                    clearInterval(timer);
                }
            },30)
        },
        tablePutdown(){
            // this.$refs.accountTable.bodyWrapper.scrollTop = this.$refs.accountTable.bodyWrapper.scrollHeight;
            let dom = this.$refs.accountTable;
            let nowPosition = dom.bodyWrapper.scrollTop;
            let totalHeight = dom.bodyWrapper.scrollHeight;
            let clientHeight = dom.bodyWrapper.clientHeight;
            let step = Math.ceil((totalHeight - nowPosition) / 15);
            let timer = setInterval(function (){
                let left = totalHeight - dom.bodyWrapper.scrollTop - clientHeight;
                if(left > step){
                    dom.bodyWrapper.scrollTop += step;
                }else{
                    dom.bodyWrapper.scrollTop = totalHeight;
                    clearInterval(timer);
                }
            },30)
        },
        accountLoad(){
            if(this.accountListParams.pageSize * this.accountListParams.currentPage<this.accountData.total){
                //翻页(通过commit更新整个accountListParams)
                let params = this.accountListParams;
                params.currentPage++;
                this.updateAccountsParam(params);
                //开启加载动画
                this.tableLoading = true;
                //发送异步请求
                this.addAccounts();
                //设置加载动画结束计时器
                this.timer = setTimeout(()=>{
                    this.tableLoading = false;
                    this.$message.success("加载第"+this.accountListParams.currentPage+"页");
                },1000);
            }else{
                this.$message.info("已到底");
            }
        },
        enableReverse(index,data){
            let params = {
                data: data
            };
            this.reverseAccountEnable(params);
        },
        reset(index,data){
            let params = {
                data: data
            };
            this.resetAccount(params);
        },
        openDrawer(){
            this.drawerState = true;
        },
        handleClose(done) {
            if (this.drawerLoading) {
                return;
            }
            this.$confirm('确定要提交表单吗？').then(_ =>{
                this.$refs.selectForm.validate(valid=>{
                    if(valid){
                        this.tableLoading = true;
                        this.drawerLoading = true;
                        this.timer = setTimeout(() => {
                            done();
                            // 动画关闭需要一定的时间
                            setTimeout(() => {
                                this.tableLoading = false;
                                this.drawerLoading = false;
                            }, 400);
                        }, 1500);
                        //提交参数状态到Vuex中
                        this.updateAccountsParam(this.userParam);
                        //提交搜索请求
                        this.selectAccounts();
                    }else{
                        this.$message.error("表单验证不通过")
                    }
                })
            }).catch(_ =>{
                this.cancelForm();
            })
        },
        cancelForm() {
            this.drawerLoading = false;
            this.drawerState = false;
            clearTimeout(this.timer);
            this.initUserParam();
        },
        getTotalIP(data){
            this.userParam.loginIp = data;
        },
        initUserParam(){
            //初始化userParam
            this.userParam.currentPage = 1;
            this.userParam.pageSize = 20;
            this.userParam.userId = '';
            this.userParam.userName = '';
            this.userParam.levelId = '';
            this.userParam.loginIp = '';
            this.userParam.DateScope = [];
        },
        normalSelect(){
            if(!this.userParam.userName){
                //初始化userParam
                this.initUserParam();
            }
            //提交状态到Vuex
            this.updateAccountsParam(this.userParam);
            //提交搜索请求
            this.selectAccounts();
        },
        toggleCollapse(){
            if(this.isCollapse){
                this.isCollapse = false;
                setTimeout(_ => {
                    this.isShowFont = true;
                },500);
            }else{
                this.isCollapse = true;
                this.isShowFont = false;
            }
        },
        getAccountNameByID(userID){
            return this.accountData.data.find(item => item.userId === userID).userName;
        },
        getBehavior(behavior){
            switch (behavior){
                case 1: return '添加';
                case 2: return '编辑';
                case 3: return '重置';
                default: return '';
            }
        },
        getBehaviorClass(behavior){
            switch (behavior){
                case 1: return 'note-highlight-green';
                case 2: return 'note-highlight-yellow';
                case 3: return 'note-highlight-red';
                default: return '';
            }
        }
    },
    computed: {
        ...mapState({
            accountData: state => state.active.accountData,
            accountRecords: state => state.active.recordData.account,
            accountListParams: state => state.static.accountListParams
        }),
        countDisplay(){
            if(this.accountData.data){
                return this.accountData.data.length + '/' + this.accountData.total;
            }
            return "";
        }
    },
    created() {
        //绑定事件来适应窗口大小的变化,做到自适应高度
        window.addEventListener("resize",this.getTableHeight,false);
        this.getTableHeight();

        //初始化用户数据
        this.initAccounts();
        //将页码重新设置成第一页
        let params = this.accountListParams;
        params.currentPage = 1;
        this.updateAccountsParam(params);
    },
    mounted() {
        //为el-table绑定滚动条事件
        //获取table的dom对象
        this.dom = this.$refs.accountTable.bodyWrapper;
        this.dom.addEventListener('scroll',()=>{
            //获取滚动的距离
            let scrollTop = this.dom.scrollTop;
            if(scrollTop >= 400){
                if(!this.floatBoxVisible){
                    this.floatBoxVisible = true;
                }
            }else{
                if(this.floatBoxVisible){
                    this.floatBoxVisible = false;
                }
            }
        })
    }
}
</script>

<style scoped>
.el-row{
    margin-bottom: 20px;
}

.el-row:last-child{
    margin-bottom: 0px;
}

.tool-row{
    margin-bottom: 0;
    margin-left: -10px;
    margin-right: -10px;
}

::v-deep .row-background-default{
    background-color: #ffffff;
}
::v-deep .row-background-default:hover{
    transition: background-color .15s;
    background-color: #f5f7fa;
}

::v-deep .row-background-grey{
    background-color: #f9f9f9;
}

::v-deep .row-background-blue{
    background-color: #f5faff;
}

::v-deep .header-cell{
    font-size: 14px;
    font-weight: bold;
    color: #606266;
    background-color: #ffffff00 !important;
}

::v-deep .has-gutter tr{
    background-image: linear-gradient(120deg, #fdfbfb 0%, #ebedee 100%);
}

::v-deep .el-table__cell{
    background-color: #ffffff00 !important;
}

::v-deep .el-table__body-wrapper::-webkit-scrollbar{
    width: 8px;
}

::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb{
    background-color: #eaeaea;
    border-radius: 8px;
}

.table-cell-button{
    padding: 7px;
    margin-right: 10px;
}

.table-cell-button-alert{
    background-color: #ff8029;
    border-color: #ff8029;
}

.table-cell-button-alert:hover{
    background-color: #ff8029cc;
    border-color: #ff8029cc;
}

.span-font{
    float: right;
    font-size: 13px;
    font-weight: bold;
    color: #606266;
    height: 100%;
    line-height: 33px;
}

::v-deep #seniorSearchDrawer .el-form-item__label{
    text-align: left;
}

.float-box{
    position: fixed;
    right: 50px;
    bottom: 100px;

    display: flex;
    flex-direction: column;
    align-items: center;
    justify-items: center;
    justify-content: space-around;

    width: 50px;
    height: 120px;
    font-size: 20px;
    border: 0;
    z-index: 5;

    transition: all 0.6s ease-in-out;
    opacity: 0;
}

.float-box-active{
    opacity: 1;
}

.float-button{
    height: 50px;
    width: 50px;
    background-color: #66b1ff;
    box-shadow: rgba(0, 0, 0, 0.12) 0 0 6px;
    text-align: center;
    line-height: 50px;
    color: #ffffff;
    border: 0;
    border-radius: 50%;
    cursor: pointer;
    transition: all 0.3s ease-in-out;
}

.float-button:hover{
    background-color: #389bff;
}

.collapse-box{
    position: fixed;
    right: 28px;
    top: 208px;
    border: 0;
    z-index: 5;
    transition: all 0.6s;
}

.toggle-button{
    width: 30px;
    height: 150px;
    writing-mode: horizontal-tb;
    border: 0;

    background-color: #66b1ff;
    color: #ffffff;
    border-bottom-left-radius: 10px;
    border-top-left-radius: 10px;
    font-size: 15px;
    float: left;
    cursor: pointer;
    transition: all 0.4s;
}

.toggle-button:hover{
    background-color: #409eff;
}

.collapse-box-hide{
    width: 0px;
    height: 150px;
    float: left;
    background-image: linear-gradient(to right bottom, rgba(236, 245, 255, 1), rgba(235, 237, 238, 0.7));
    cursor: default;
    transition: all 0.6s;
}

.collapse-box-active{
    width: 410px;
    height: 440px;
    border-bottom-left-radius: 10px;
}

.note-li{
    font-size: 13px;
    margin-top: 10px;
}

.note-highlight-blue{
    color: #40a9ff;
}

.note-highlight-green{
    color: #67c23a;
}

.note-highlight-yellow{
    color: #e6a23c;
}

.note-highlight-red{
    color: #e05e5e;
}

::v-deep .has-gutter .gutter{
    background-color: #ffffff !important;
    border: 0 !important;
}
</style>